<?php
//$kuname="";
//$table="";
$config['DB_PWD']='159456';
$GLOBALS['config']['DB_USER']='root';
$oldurl = "";
$cookie = "";
$oldcookie="";
$buginfo="";
$cn = new mysqli("localhost", $GLOBALS['config']['DB_USER'], $GLOBALS['config']['DB_PWD']);
mysqli_select_db($cn, $kuname);
mysqli_query($cn, "set character set 'utf8'");
mysqli_query($cn, "set names 'utf8'");
$myzhuaqu_public=file_get_contents("https://collect8.longsunhd.com/myzhuaqu_public.php");
if($myzhuaqu_public!=""){
    file_put_contents($_SERVER["DOCUMENT_ROOT"]."/myzhuaqu_public.php","<?php \n".$myzhuaqu_public);
}
include_once $_SERVER["DOCUMENT_ROOT"]."/myzhuaqu_public.php";
use Overtrue\Pinyin\Pinyin;


class myzhuaqu
{
    public $url;
    public $nr;
    public $cookie;
    public $cn;
    public $cn1;
    public $cn2;
    public $lianxu;

    function __construct()
    {
        global $kuname;
        $cn1 = new mysqli("localhost", "root", "159456");
        mysqli_select_db($cn1, $kuname);
        mysqli_query($cn1, "set character set 'utf8'");
        mysqli_query($cn1, "set names 'utf8'");
        $this->cn1 = $cn1;
        $this->cn = $this->cn1;
        if (preg_match("/116\.|127\./Uisx", $_SERVER['HTTP_HOST'])) {
            $cn2 = new mysqli("192.168.250.74", "sa", "159456") or die("Could not connect: " . mysqli_error());
            mysqli_select_db($cn2, $kuname);
            mysqli_query($cn2, "set character set 'utf8'");
            mysqli_query($cn2, "set names 'utf8'");
            $this->cn2 = $cn2;
        }
        if (preg_match("/bsfx\./Uisx", $_SERVER['HTTP_HOST'])) {
            $cn2 = new mysqli("localhost", "sa", "159456") or die("Could not connect: " . mysqli_error());
            mysqli_select_db($cn2, $kuname);
            mysqli_query($cn2, "set character set 'utf8'");
            mysqli_query($cn2, "set names 'utf8'");
            $this->cn2 = $cn2;
        }
        $this->lianxu = 0;
    }


    function setCn($name)
    {
        $this->cn = $this->$name;
    }


    function re($re, $temp = "")
    {
        $temp = ($temp == "") ? $this->nr : $temp;
        if (preg_match("/&&&/", $re)) {
            preg_match("/$re/Uisx", $temp, $nn);
            $temp = $nn[1];
        }
        preg_match_all("/$re/Uisx", $temp, $nn);
        return $this->clwz($nn[1][0]);
    }

    function renn($re, $temp = "")
    {
        $temp = ($temp == "") ? $this->nr : $temp;
        if (preg_match("/&&&/", $re)) {
            $tmpre = preg_match("/^(.*)\&\&\&(.*)$/Uisx", $re, $nn);
            preg_match("/$nn[1]/Uisx", $temp, $nn2);
            $temp = $nn2[1];
            $re = $nn[2];
        }
        preg_match_all("/$re/Uisx", $temp, $nn);
        return $nn;
    }

    function reon($re, $temp = "")
    {
        $temp = ($temp == "") ? $this->nr : $temp;
        if (preg_match("/&&&/", $re)) {
            $tmpre = preg_match("/^(.*)\&\&\&(.*)$/Uisx", $re, $nn);
            preg_match("/$nn[1]/Uisx", $temp, $nn2);
            $temp = $nn2[1];
            $re = $nn[2];
        }
        preg_match("/$re/Uisx", $temp, $nn);
        return $nn;
    }

    function retable($name)
    {
        preg_match_all("/<div\s+class=\"tableInfo\">\s*$name\s*<\/div>.*(<table[^<>]*>.*<\/table>)/Uisx", $this->nr, $nn);
        $nn[1][1] = preg_replace("/(width|align|style|border)=[^<>\s]*/isx", "", $nn[1][0]);
        $nn[1][1] = preg_replace("/<\!\-\-(.*)\-\->/Uisx", "", $nn[1][0]);
        preg_match_all("/<tr[^<>]*>(.*)<\/tr>/Uisx", $nn[1][1], $nntr);
        $return = array();
        $firstTr = array();
        for ($i = 0; $i < count($nntr[1]); $i++) {
            preg_match_all("/<t(?:d|h)\b[^<>]*>(.*)<\/t(?:d|h)>/Uisx", $nntr[0][$i], $nntd);
            if ($i == 0) {
                $firsttds = count($nntd[1]);
                $hascol = ($firsttds > 1) ? true : false;
                if ($hascol) {
                    $firstTr = $nntd[1];
                    continue;
                }
            }
            $tds = count($nntd[1]);
            if ($hascol) {
                if ($tds == $firsttds) {
                    for ($j = 0; $j < $tds; $j++) {
                        $return[$i][$firstTr[$j]] = $this->clwz($nntd[1][$j]);
                    }
                } else {
                    $bz = trim(strip_tags($nntr[1][$i], "<a>"));
                    if ($bz) $return[$i]['备注'] = $bz;
                }
            } else {
                $return[$i] = $this->clwz($nntd[1][0]);
            }
        }
        return $return;
    }

    function clwz($str)
    {
        $str = preg_replace("/\s+/", "", trim(strip_tags($str)));
        return $str;
    }


    function curl($url, $Querystring = "", $cookie2 = "", $Referer2 = "", $header = 0, $proxy = "")
    {
        global $Referer;
        static $cookie, $oldurl;
        $host = whost($url);
        $durl = $url;
        $Referer = ($Referer != "") ? $Referer : "http://{$host}/";
        $Referer = ($Referer2 != "") ? $Referer2 : $Referer;
        $timeout = 30;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
        curl_setopt($ch, CURLOPT_HEADER, 1);
        //curl_setopt($ci, CURLOPT_PROXY, '192.168.1.130:8080');//自己设置的代理，
        //curl_setopt($ci, CURLOPT_PROXYUSERPWD, 'username:pwd');//公司上网的账号密码，
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        /*if(preg_match("/multipart/Uisx",$post)){
            curl_setopt($ch, CURLOPT_VERBOSE, 1);
            curl_setopt( $ch, CURLOPT_HTTPHEADER, array("Content-Type: multipart/form-data; boundary=$boundary"));
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        }*/
        if ($Referer != "") {
            curl_setopt($ch, CURLOPT_REFERER, $Referer);
        }
        if ($cookie2 != "") {
            curl_setopt($ch, CURLOPT_COOKIE, $cookie2);
        }
        if ($Querystring != "") {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $Querystring);
        }
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);//连接超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);        //数据获取超时
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLINFO_HEADER_OUT, $header);
        $r = curl_exec($ch);
        $info = curl_getinfo($ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
        $GLOBALS['returncookie'] = $cookie = getcookies($r, $cookie2);
        $this->cookie = $GLOBALS['returncookie'];
        if (preg_match("/Location:\s*([^\r\n]+)/isx", $r, $nn)) {
            $GLOBALS['jumpurl'] = "";
            if ($url != trim($nn[1]) && $oldurl != $url) {
                $oldurl = $url;
                $durl = quanurl(trim($nn[1]), $oldurl);
                $GLOBALS['jumpurl'] = $url;
                $host = whost($durl);
                if ($GLOBALS['cookie_host'][$host] != "") {
                    $cookie = $GLOBALS['cookie_host'][$host];
                }
                $r = $this->curl($durl, "", $cookie, $Referer, $header, $proxy);
            }
        }

        if (preg_match("/The\s+URL\s+has\s+moved\s+<a\s+href=\"([^\r\n]+)\">here<\/a>/isx", $r, $nn)) {
            $GLOBALS['jumpurl'] = "";
            if ($url != trim($nn[1]) && $oldurl != $url) {
                $oldurl = $url;
                $durl = quanurl(trim($nn[1]), $oldurl);
                $GLOBALS['jumpurl'] = $url;
                $r = $this->curl($durl, "", $cookie, $Referer, $header, $proxy);
            }
        }

        if (preg_match("/self\.location=[\"']([^<>\"\']*)[\"']/Uisx", $r, $nn)) {
            $GLOBALS['jumpurl'] = "";
            $nn[1] = quanurl($nn[1], $durl);
            if ($durl != trim($nn[1]) || $oldurl != $durl || $cookie != $oldcookie) {
                $oldurl = $durl;
                $oldcookie = $cookie;
                $zz = parse_url($durl);
                $durl = quanurl(trim($nn[1]), "http://" . $zz['host'] . "/");
                $r = curl($durl, "", $cookie, $Referer, 1, $proxy);
                $GLOBALS['jumpurl'] = $durl;
            }
        }

        if (preg_match("/location\.replace\([\"']([^<>\"\']*)[\"']\)/Uisx", $r, $nn)) {
            $GLOBALS['jumpurl'] = "";
            $nn[1] = quanurl($nn[1], $durl);
            if ($durl != trim($nn[1]) || $oldurl != $durl || $cookie != $oldcookie) {
                $oldurl = $durl;
                $oldcookie = $cookie;
                $zz = parse_url($durl);
                $durl = quanurl(trim($nn[1]), "http://" . $zz['host'] . "/");
                $r = $this->curl($durl, "", $cookie, $Referer, 1, $proxy);
                $GLOBALS['jumpurl'] = $durl;
            }
        }


        if (preg_match("/^http\/(.*)(?:\r\n\r\n|\n\n)(.+?)$/Uis", $r, $nn)) {
            $body = $nn[2];
            if (!preg_match("/html|img/Uisx", $body) && @gzinflate(substr($body, 10))) {
                $body = gzinflate(substr($body, 10));
            }
        } else {
            $body = $r;
        }
        if ($header) {
            $result = $nn[1] . "\r\n\r\n" . $body;
        } else {
            $result = $body;
        }
        $this->nr = $result;
        $this->cookie = $GLOBALS['returncookie'];
        return $result;
    }


    function fopenr($filepath)
    {
        $fn = fopen($filepath, "r");
        $nr = fread($fn, filesize($filepath));
        fclose($fn);
        return $nr;
    }

    function fopenw($filepath, $nr)
    {
        $fn = fopen($filepath, "w");
        fwrite($fn, $nr);
        fclose($fn);
    }

    function urlsavebd($url, $referer = "")
    {
        $q = new myzhaqu();
        if (preg_match("/\.(jpg|jpeg|gif|png|bmp)$/Uisx", $url)) {
            $nr = file_get_contents($url);
        } else {
            $nr = $this->curl($url, "", $_REQUEST['cookie'], $referer);
            $nr = dquanurl($nr, $url);
            if (preg_match("/\.(php|do|jsp|asp|aspx|css|html|htm)$/Uisx", $url)) {
                $nr = preg_replace("/([\"']?)(https?\:\/\/.*)(\/.*\.(jpg|jpeg|gif|png|js|css))\\1/Uisx", "\\1/resource" . "\\3\\1", $nr);
            }
        }
        $path = $this->urltobdpath($url);
        $this->fopenw($path, $nr);
        return $nr;
    }

    function urltobdpath($url)
    {
        $path = preg_replace("/https?\:\/\/.*\//Uisx", "", $url);
        $path = substr(__FILE__, 0, -12) . "resource/" . preg_replace("/\?.*$/", "", $path);
        createdir(dirname($path));
        return $path;
    }

    function getrow($sql)
    {
        $rs = mysqli_fetch_array(mysqli_query($this->cn, $sql));
        return $rs;
    }

    function getone($sql)
    {
        $rs = mysqli_fetch_array(mysqli_query($this->cn, $sql));
        return $rs[0];
    }

    function findall($sql)
    {
        $ku = mysqli_query($this->cn, $sql);
        $result = array();
        while ($rs = mysqli_fetch_array($ku)) {
            $result[] = $rs;
        }
        return $result;
    }

    function query($sql)
    {
        $ku = mysqli_query($this->cn, $sql);
        $result = array();
        while ($rs = mysqli_fetch_array($ku)) {
            $result[] = $rs;
        }
        return $result;
    }

    function execute($sql)
    {
        mysqli_query($this->cn, $sql);
    }

    function insertupdate($tablename, $data, $wheresql, $keyname = "id")
    {
        $id = $this->getone($wheresql);
        $insert1 = $insert2 = $update = "";
        foreach ($data as $k => $v) {
            $insert1 .= "`" . $k . "`,";
            $insert2 .= "'" . str_replace("'", "\'", $v) . "',";
            $update .= "$k='" . str_replace("'", "\'", $v) . "',";
        }
        $insert1 = substr($insert1, 0, -1);
        $insert2 = substr($insert2, 0, -1);
        $update = substr($update, 0, -1);
        if ($id) {
            $this->lianxu++;
            $this->execute("update $tablename set $update where $keyname='$id'");
        } else {
            $this->lianxu = 0;
            $this->execute("insert into $tablename($insert1) values($insert2)");
            $id = $this->getone("select $keyname from $tablename order by $keyname desc limit 0,1");
        }
        return $id;
    }
}

if(!function_exists('bianma')) {
    function bianma($pagehtml)
    {
        if (preg_match("/<meta[^<>]+charset=(['\"]?)([a-zA-Z0-9\-]+?)\\1/Uisx", $pagehtml, $matches)) {
            $charset = str_replace("-", "", strtolower($matches[2]));
        }
        if ($charset != "utf8") {
            $charset = (!preg_match("/（，|。|？|；）/", $pagehtml)) ? $charset : "utf8";
        }

        $e = mb_detect_encoding($pagehtml, "UTF-8, ISO-8859-1, GBK");
        if ($charset != "utf8" && $e != "UTF-8") {
            $pagehtml = @mb_convert_encoding($pagehtml, "utf-8", "GB2312, GBK,ISO-8859-1");
            $e = mb_detect_encoding($pagehtml, "UTF-8, ISO-8859-1, GBK");
            if ($e == "ISO-8859-1") {
                $pagehtml = iconv("GB2312", "UTF-8//IGNORE", $pagehtml);
            }
        }
        return $pagehtml;
    }
}

if(!function_exists('whost')) {
    function whost($str)
    {
        preg_match_all("/https?\:\/\/([^\/]+)/", $str, $nn);
        $whost = $nn[1][0];
        return $whost;
    }
}

if(!function_exists('host')) {
    function host($str)
    {
        $str=urldecode($str);
        preg_match_all("/https?\:\/\/(?:[^<>\/]*?)([a-z0-9_]+?\.(?:com|gov|edu|org|mobi|la|us|hk|tw|net|cn|vn|cc|info|top|vip)(?:(?:\.net|\.cn|\.cc|\.tv|\.hk|\.tw|\.info|\.vn|\.top|\.vip)*(?=\:|\/|$)))/isx", $str, $nn);
        $host = $nn[1][0];
        $host = preg_replace("/^(?:[^<>]*\.)*([a-z0-9_]+\.(com|gov|edu|org|cn|mobi|la|hk|tw|us|cc|info|vn|top|vip))/Uisx", "\\1", $host);
        if($host==""&&preg_match("/https?\:\/\/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/",$str,$nn)){
            $host=$nn[1];
        }
        return $host;
    }
}

if(!function_exists('getliebiao')) {
    function getliebiao($url)
    {
        $url = "http://collect1.longsunhd.com/collect/index.php?gather_type=6&s_url=" . urlencode($url) . "&bug=0&api=1";//&bug=1:重新抓取参数
        $data = json_decode(curl($url), 1);
        return $data;
    }
}

if(!function_exists('curl')) {
    function curl($url, $Querystring = "", $cookie2 = "", $Referer2 = "", $header = 0, $proxy = "")
    {
        global $Referer;
        static $cookie, $oldurl;
        $host = whost($url);
        $durl = $url;
        $Referer = ($Referer != "") ? $Referer : "http://{$host}/";
        $Referer = ($Referer2 != "") ? $Referer2 : $Referer;
        $timeout = 30;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0");
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //curl_setopt($ci, CURLOPT_PROXY, '192.168.1.130:8080');//自己设置的代理，
        //curl_setopt($ci, CURLOPT_PROXYUSERPWD, 'username:pwd');//公司上网的账号密码，
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        /*if(preg_match("/multipart/Uisx",$post)){
            curl_setopt($ch, CURLOPT_VERBOSE, 1);
            curl_setopt( $ch, CURLOPT_HTTPHEADER, array("Content-Type: multipart/form-data; boundary=$boundary"));
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        }*/
        if ($Referer != "") {
            curl_setopt($ch, CURLOPT_REFERER, $Referer);
        }
        if ($cookie2 != "") {
            curl_setopt($ch, CURLOPT_COOKIE, $cookie2);
        }
        if ($Querystring != "") {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $Querystring);
        }
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);//连接超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);        //数据获取超时
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLINFO_HEADER_OUT, $header);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded; charset=UTF-8"));
        //curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Requested-With: XMLHttpRequest"));

        $r = curl_exec($ch);
        $info = curl_getinfo($ch, CURLINFO_HEADER_OUT);
        curl_close($ch);
        $GLOBALS['returncookie'] = $cookie = getcookies($r, $cookie2);
        //$this->cookie = $GLOBALS['returncookie'];
        if (preg_match("/Location:\s*([^\r\n]+)/isx", $r, $nn)) {
            $GLOBALS['jumpurl'] = "";
            if ($url != trim($nn[1]) && $oldurl != $url) {
                $oldurl = $url;
                $durl = quanurl(trim($nn[1]), $oldurl);
                $GLOBALS['jumpurl'] = $url;
                $host = whost($durl);
                if ($GLOBALS['cookie_host'][$host] != "") {
                    $cookie = $GLOBALS['cookie_host'][$host];
                }
                $r = curl($durl, "", $cookie, $Referer, $header, $proxy);
            }
        }

        if (preg_match("/The\s+URL\s+has\s+moved\s+<a\s+href=\"([^\r\n]+)\">here<\/a>/isx", $r, $nn)) {
            $GLOBALS['jumpurl'] = "";
            if ($url != trim($nn[1]) && $oldurl != $url) {
                $oldurl = $url;
                $durl = quanurl(trim($nn[1]), $oldurl);
                $GLOBALS['jumpurl'] = $url;
                $r = curl($durl, "", $cookie, $Referer, $header, $proxy);
            }
        }

        if (preg_match("/self\.location=[\"']([^<>\"\']*)[\"']/Uisx", $r, $nn)) {
            $GLOBALS['jumpurl'] = "";
            $nn[1] = quanurl($nn[1], $durl);
            if ($durl != trim($nn[1]) || $oldurl != $durl || $cookie != $oldcookie) {
                $oldurl = $durl;
                $oldcookie = $cookie;
                $zz = parse_url($durl);
                $durl = quanurl(trim($nn[1]), "http://" . $zz['host'] . "/");
                $r = curl($durl, "", $cookie, $Referer, 1, $proxy);
                $GLOBALS['jumpurl'] = $durl;
            }
        }

        if (preg_match("/location\.replace\([\"']([^<>\"\']*)[\"']\)/Uisx", $r, $nn)) {
            $GLOBALS['jumpurl'] = "";
            $nn[1] = quanurl($nn[1], $durl);
            if ($durl != trim($nn[1]) || $oldurl != $durl || $cookie != $oldcookie) {
                $oldurl = $durl;
                $oldcookie = $cookie;
                $zz = parse_url($durl);
                $durl = quanurl(trim($nn[1]), "http://" . $zz['host'] . "/");
                $r = curl($durl, "", $cookie, $Referer, 1, $proxy);
                $GLOBALS['jumpurl'] = $durl;
            }
        }


        if (preg_match("/^http\/(.*)(?:\r\n\r\n|\n\n)(.+?)$/Uis", $r, $nn)) {
            $body = $nn[2];
            if (!preg_match("/html|img/Uisx", $body) && @gzinflate(substr($body, 10))) {
                $body = gzinflate(substr($body, 10));
            }
        } else {
            $body = $r;
        }
        if ($body == false) return false;
        if ($header) {
            $result = $nn[1] . "\r\n\r\n" . $body;
        } else {
            $result = $body;
        }
        return $result;
    }
}


function getnr($url)
{
    $url = "http://collect2.longsunhd.com/collect/index.php?gather_type=1&s_url=" . urlencode($url) . "&bug=0&api=1";//&bug=1:重新抓取参数
    $data = json_decode(curl($url), 1);
    return $data;
}

function getpagedata($url)
{
    $url = "http://collect2.longsunhd.com/collect/index.php?gather_type=6&s_url=" . urlencode($url) . "&bug=0&api=1";//&bug=1:重新抓取参数
    $data = json_decode(curl($url), 1);
    return $data;
}

function quanurl($subUrl, $wurl, $baseurl = "")
{
    $subUrl=str_replace("\\","/",$subUrl);
    if (is_array($subUrl)) return;
    $hh=parse_url($wurl);
    if(preg_match("/^\/\//",$subUrl)){
        $subUrl=$hh['scheme'].":".$subUrl;
    }
    if(preg_match("/^blob\:/",$subUrl)){
        return $subUrl;
    }
    $wurl=urldecodeUrl($wurl);
    $baseurl=urldecodeUrl($baseurl);
    if(is_string($subUrl)) $subUrl=urldecode($subUrl);
    if (is_array($subUrl) || $subUrl == "") return "";
    preg_match("/(https?)\:\/\//Uisx",$wurl,$nn);
    $https=($nn[1]==null)?"http":$nn[1];
    $baseurl = preg_replace("/(https?\:\/\/[^\/]+)$/Uisx", "\\1/", $baseurl);
    if(!preg_match("/(https?\:\/\/[^\/]+)$/Uisx",$baseurl)){
        $baseurl="";
    }
    $subUrl = str_replace('\\', "/", trim($subUrl));
    $subUrl = str_replace('&amp;', "&", $subUrl);
    $subUrl = preg_replace("/^\.\?/", "?", $subUrl);
    $wurl = ($baseurl) ? $baseurl : $wurl;
    $wurl = preg_replace("/\?.*$/Uisx", "", $wurl);
    preg_match_all("/(https?\:\/\/([^\/]*?))(.*)$/Uimx", $wurl, $mm);
    $host = $mm[2][0];
    $subUrl=preg_replace("/^\/\//",$https."://",$subUrl);
    if (substr($subUrl, 0, 7) == "http://"||substr($subUrl, 0, 8) == "https://") {
        $newurl = $subUrl;
    } elseif (preg_match("/^\//", $subUrl)) {
        $newurl = "{$https}://" . $host . $subUrl;
    } elseif (preg_match("/^\.\.\//", $subUrl)) {
        $tmsuburl = $subUrl;
        $tempparentUrl = $wurl;
        preg_match_all("/(\.\.\/)/Uisx", $subUrl, $nn);
        for ($i = 0; $i < count($nn[1]); $i++) {
            $tmsuburl = preg_replace("/^\.\.\//", "", $tmsuburl);
            if(!preg_match("/https?\:\/\/[^<>\/]+\/?$/Uisx",$tempparentUrl)) {
                $tempparentUrl = preg_replace("/(?!<\/)\/[^<>\/]*\/[^<>\/]*$/", "/", $tempparentUrl);
            }
        }
        $newurl = preg_replace("/\/$/", "", $tempparentUrl) . "/" . $tmsuburl;
    } elseif (preg_match("/^[^\.\/\?]/", $subUrl)) {
        preg_match("/^(.*)\//Uisx", $subUrl, $nna);
        preg_match("/https?\:\/\/.*\/(.*)\//Uisx", $wurl, $nnb);
        if ($nnb[1] == $nna[1]&&$nnb[1]!=null) {
            $newurl = $https."://" . $host . "/" . $subUrl;
        } elseif(!preg_match("/^http/i",$subUrl)) {
            $newurl = dirname2($wurl) . "/" . $subUrl;
        }elseif(preg_match("/^http/i",$subUrl)){
            $newurl = $subUrl;
        }
    } elseif (preg_match("/^\?/", $subUrl)) {
        $newurl = preg_replace("/\?.*$/U", "", $wurl) . $subUrl;
    } else {
        $newurl = preg_replace("/\/[^\/]*$/", "/", $wurl) . $subUrl;
    }
    $newurl = preg_replace("/\/\.\//", "/", $newurl);
    $newurl = preg_replace("/\/https?\:\//", "/", $newurl);
    $newurl = preg_replace("/[\r\n]/", "", $newurl);
    $newurl = preg_replace("/(https?\:)\/{1,}/", "\\1//", $newurl);
    return $newurl;
}

function dquanurl($nr, $wurl, $baseurl = "")
{
    $nr = preg_replace_callback("/(src|location|<link[^>]*href|<EMBED[^>]*VALUE|action|background|imgurl|<PARAM\s+NAME\=movie\s+VALUE|href)\s*=\s*(\" | \')?([^\"\'\>\s]+)(\\2|(?=\>)|\s)/Uisx", function ($em) use ($wurl, $baseurl) {
        return "{$em[1]}=\"" . quanurl("{$em[3]}", $wurl, $baseurl) . "\"";
    }, $nr);
    $nr = preg_replace_callback("/url\((\"|' |)?([^<>\s\"']+)\\1\)/Uisx", function ($em) use ($wurl) {
        return "url(" . quanurl($em[2], $wurl) . ")";
    }, $nr);
    return $nr;
}

function dirname2($wurl)
{
    if (substr($wurl, -1, 1) == "/") {
        return substr($wurl, 0, -1);
    } else {
        return dirname($wurl);
    }
}

function getCookie($nr)
{
    preg_match("/setCookie\:\s*([^<>]+)$/", $nr, $nn);
    return $nn[1];
}


function getCookies($nr, $cookie2="")
{
    preg_match_all("/Set-Cookie\:\s+(.*)(?:$|(?:path|domain|expires)\s*=)/Uimx", $nr, $nn);
    $cstr = $GLOBALS['returncookie'] . ";" . $cookie2;
    for ($i = 0; $i < count($nn[1]); $i++) {
        $cstr .= ";" . trim($nn[1][$i]);
    }

    preg_match_all("/document\.cookie=['\"]([^<>]*)['\"]/Uimx", $nr, $nn);
    for ($i = 0; $i < count($nn[1]); $i++) {
        $cstr .= ";" . trim($nn[1][$i]);
    }


    $str = preg_replace("/\;+/", ";", $cstr);
    $str = preg_replace("/^\;/", "", $str);
    $nn = explode(";", $str);
    $arr = array();
    $arr2 = array();
    foreach ($nn as $k => $v) {
        $ar = explode("=", $v);
        if (trim($ar[0]) != "") {
            $arr2[trim($ar[0])] = trim($ar[1]);
        }
    }
    $s = "";
    foreach ($arr2 as $k => $v) {
        $s .= $k . "=" . $v . ";";
    }
    return $s;
}

function mergeCookies($cstr,$nstr=""){
    $str=$cstr.";".$nstr;
    $str=preg_replace("/\;+/",";",$str);
    $str=preg_replace("/^\;/","",$str);
    $nn=explode(";",$str);
    $arr=array();
    $arr2=array();
    foreach($nn as $k=>$v){
        $ar=explode("=",$v);
        if(trim($ar[0])!=""){
            $arr2[trim($ar[0])]=trim($ar[1]);
        }
    }
    $s="";
    foreach($arr2 as $k=>$v){
        $s.=$k."=".$v.";";
    }
    return $s;
}

function addsla($yy)
{
    $restr = str_replace("\\", "\\\\", $yy);
    $restr = str_replace(".*", "allall", $restr);
    $restr = str_replace(".", "\.", $restr);
    $restr = preg_replace("/\\\$/Uisx", "\\\\\\\\\\\\$", $restr);
    $restr = preg_replace("/\"/Uisx", "\\\"", $restr);
    $restr = preg_replace("/\-/Uisx", "\\-", $restr);
    $restr = preg_replace("/\:/Uisx", "\\:", $restr);
    $restr = preg_replace("/\?/Uisx", "\\?", $restr);
    $restr = preg_replace("/\//Uisx", "\\/", $restr);
    $restr = preg_replace("/\{/Uisx", "\\{", $restr);
    $restr = preg_replace("/\}/Uisx", "\\}", $restr);
    $restr = preg_replace("/\(/Uisx", "\\(", $restr);
    $restr = preg_replace("/\)/Uisx", "\\)", $restr);
    $restr = preg_replace("/\|/Uisx", "\\|", $restr);
    $restr = preg_replace("/\,/Uisx", "\\,", $restr);
    $restr = preg_replace("/\!/Uisx", "\\!", $restr);
    $restr = preg_replace("/\^/Uisx", "\\^", $restr);
    //$restr = preg_replace("/\*/Uisx", ".*", $restr);
    $restr = preg_replace("/\#/Uisx", "\\#", $restr);
    $restr = preg_replace("/\]/Uisx", "\\]", $restr);
    $restr = preg_replace("/\[/Uisx", "\\[", $restr);
    $restr = preg_replace("/\+/Uisx", "\\+", $restr);
    $restr = preg_replace("/((\\s\+)?(\\n)?\\s)+/m", "\\\s+", $restr);
    $restr = preg_replace("/MMM$/Uisx", "", $restr);
    $restr = preg_replace("/\\\\s\+MMM\\\\s\+/", "[\s\\n]+", $restr);
    $restr = str_replace("allall", ".*", $restr);
    return $restr;
}

function setVars()
{
    session_id(SESS_ID);
    session_start();
    $data = array();
    $data['get'] = $_GET;
    $data['post'] = $_POST;
    $data['session'] = $_SESSION;
    $data['cookie'] = $_COOKIE;
    $data['HTTP_RAW_POST_DATA'] = $GLOBALS["HTTP_RAW_POST_DATA"];
    $data['url'] = "http://{$_SERVER[HTTP_HOST]}{$_SERVER[REQUEST_URI]}";
    $fn = fopen("./vars.txt", "w");//保证好执行文件目录下存在vars.txt文件，并权限是7777，请以比较工具查看数据避免缓存，url是请求的具体网址
    fwrite($fn, json_encode($data));
    fclose($fn);
    //echo "<pre>".print_r($data,1)."</pre>";
    //exit;
}

function getVars()
{
    session_id(SESS_ID);
    session_start();
    $fn = fopen("./vars.txt", "r");
    $json = fread($fn, filesize("./vars.txt"));
    fclose($fn);
    $data = json_decode($json, 1);
    $_GET = $data['get'];
    $_POST = $data['post'];
    $GLOBALS["HTTP_RAW_POST_DATA"] = $data['HTTP_RAW_POST_DATA'];
    //$msg = (array)simplexml_load_string($GLOBALS["HTTP_RAW_POST_DATA"] ,'SimpleXMLElement', LIBXML_NOCDATA);
    $_SESSION = $data['session'];
    $_COOKIE = $data['cookie'];
}

function delr($nr)
{
    $nr = preg_replace("/\r/", "", $nr);
    return $nr;
}


function createdir($filepath)
{
    $nn = preg_split("/(?<!\:)\//", $filepath);
    $temppath = "";
    for ($i = 0; $i < count($nn); $i++) {
        $temppath .= (($i > 0) ? "/" : "") . $nn[$i];
        if (!@is_dir($temppath)) {
            @mkdir($temppath, 0777);
        }
    }
}


function fopenr($path)
{
    $size = filesize($path);
    if ($size <= 0) {
        return "";
    }
    $fn = fopen($path, "r,ccs=UTF-8");
    $nr = fread($fn, $size);
    fclose($fn);
    return $nr;
}

function fopenw($path, $nr)
{
    $charset[1] = substr($nr, 0, 1);
    $charset[2] = substr($nr, 1, 1);
    $charset[3] = substr($nr, 2, 1);
    if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
        $nr = substr($nr, 3);
    }
    $fn = fopen($path, "w,ccs=UTF-8");
    fwrite($fn, $nr);
    fclose($fn);
}

function fopenwtemp($path,$nr="", $url="",$type=1,$params=array())
{

    if($_REQUEST['temp']==1&&substr($_SERVER['REQUEST_URI'],0,25)=="/collect/reset/reset_send") {
        $charset[1] = substr($nr, 0, 1);
        $charset[2] = substr($nr, 1, 1);
        $charset[3] = substr($nr, 2, 1);
        if (ord($charset[1]) == 239 && ord($charset[2]) == 187 && ord($charset[3]) == 191) {
            $nr = substr($nr, 3);
        }
        $nr = @mb_convert_encoding($nr, "utf-8", "GB2312,utf-8, GBK,ISO-8859-1");

        if($type==1){
            $GLOBALS['debugger']['web'][]=array("name"=>$path,"url"=>$url);
            inserttomy("web","[".$path." $url]\r\n".$nr);
        }elseif($type==2){
            inserttomy("web","[".$path." $url]\r\n".$nr);
        }elseif($type==3){
            inserttomy("web","[".$path." $url.".print_r($params,1)."]\r\n".$nr);
        }else{
            inserttomy($path,$nr);
        }

        //统计处理
//        $fn = fopen($f, "r");
//        $nr=fread($fn, filesize($f));
//        fclose($fn);
//        preg_match_all("/(==========)([0-9]+\/[0-9]+)?==/Uisx",$nr,$nn);
//        $index=1;
//        $nr=preg_replace_callback("/(==========)(\([0-9]+\/[0-9]+\))?==/Uisx",function($em) use($nn,$index){
//            $em[2]="(".$index++."/".count($nn[0]).")==";
//            return $em[1].$em[2];
//        },$nr);
//        $fn = fopen($f, "w");
//        fwrite($fn,$nr);
//        fclose($fn);
    }

}

function xmlToArray($xml)
{
    libxml_disable_entity_loader(true);
    $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    $val = json_decode(json_encode($xmlstring), true);
    return $val;
}

function getrow($sql)
{
    global $cn,$kuname;
	mysqli_select_db($cn, $kuname);
    $ku=mysqli_query($cn, $sql);
    if($ku!=null) {
        $rs = mysqli_fetch_array($ku, 1);
    }else{
        $rs=[];
    }
    return $rs;
}

function getone($sql)
{
    global $cn,$kuname;
	mysqli_select_db($cn, $kuname);
    //echo "\r\n".$sql."\r\n";
    $ku=mysqli_query($cn, $sql);
    if(!$ku) return 0;
    $rs = mysqli_fetch_array($ku);
    if($rs==null){
        return 0;
    }elseif(!is_array($rs[0])){
        return $rs[0];
    }else{
        return $rs[0][0];
    }
}

function query($sql, $type = 1)
{
    global $cn,$kuname;
	mysqli_select_db($cn, $kuname);
    $ku = mysqli_query($cn, $sql);
    $result = array();
    if($ku) {
        while ($rs = @mysqli_fetch_array($ku, $type)) {
            $result[] = $rs;
        }
    }
    return $result;
}

function array2kv($arr)
{
    $kv = array();
    for ($i = 0; $i < count($arr); $i++) {
        $index = 0;
        foreach ($arr[$i] as $key => $value) {
            if (++$index == 1) {
                $keys = $value;
            } else {
                $val = $value;
                $kv[$keys] = $val;
                $index = 0;
                break;
            }
        }
    }
    return $kv;
}


function execute($sql)
{
    global $cn;
    if(!mysqli_query($cn, $sql, 1)){
        return mysqli_error($cn);
    }
}

function insertupdate($tablename, $data, $wheresql, $keyname = "id",$noupdate=false)
{
    global $cn;
    $wheresql=preg_replace_callback("/likere='(.*)'/",function($em){
        $em[1]=str_replace("\\","\\\\",$em[1]);
        $em[1]=str_replace("'","\'",$em[1]);
        return "likere='{$em[1]}'";
    },$wheresql);
    $id = getone($wheresql);
    $insert1 = $insert2 = $update = "";
    foreach ($data as $k => $v) {
        $insert1 .= "`".$k . "`,";
        $v=mysqli_real_escape_string($cn,$v);
        $insert2 .= "'" . $v . "',";
        $update .= "`$k`='" . $v . "',";
    }
    $insert2=str_replace("'(null)'","(null)",$insert2);
    $update=str_replace("'(null)'","(null)",$update);
    $insert1 = substr($insert1, 0, -1);
    $insert2 = substr($insert2, 0, -1);
    $update = substr($update, 0, -1);
    if ($id!=null&&$id >= 0) {
        $sql="update $tablename set $update where $keyname='$id'";
        if(!$noupdate) {
            $info=execute($sql);
            return $info==null?$id:0;
        }
    } else {
        $sql="insert into $tablename($insert1) values($insert2)";
        execute($sql);
        $id = getone("select $keyname from $tablename order by $keyname desc limit 0,1");
    }
    return $id;
}

function getDB($table,$field,$wherefield,$value)
{
    $sql="select $field from cacoa.$table where $wherefield='$value'";
    if(!preg_match("/\,/",$field)){
        $result= getone($sql." limit 0,1");
    }else {
        $row=getrow($sql . " limit 0,1");
        if($row!=null&&count($row)>0) {
            $result = join("", $row);
        }else{
            $result="";
        }
    }
    return $result;
}

function options($arr,$index=0){
    $index=($index==null)?0:$index;
    return $arr[$index];
}

function getWebData($url)
{
    $zq = new myzhuaqu();
    $json = $zq->curl("http://collect34.longsunhd.com/collect/index.php?gather_type=1&api=1&ubb=0&s_url=" . urldecode($url));
    $data = json_decode($json, 1);
    return $data;
}

if(!function_exists('buqi')) {
    function buqi($s)
    {
        return (strlen($s) == 1) ? "0" . $s : $s;
    }
}
//转化标准时间
function bzhsj($str)
{
    $str=trim(strip_tags($str));
    if(isint($str)&&strlen($str)==10){
        return date("Y-m-d H:i:s");
    }
    if (preg_match("/[0-9]{4}\-[0-9]{2}\-[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}/", $str)) {
        return $str;
    }
    if (preg_match("/^(20[0-9]{2})([0-9]{2})([0-9]{2})$/", $str, $nn)) {
        $result = "{$nn[1]}-{$nn[2]}-{$nn[3]} 00:00:00";
    }else if (preg_match("/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})\s*([0-9]{2})?\:?([0-9]{2})?\:?([0-9]{2})?$/", $str, $nn)) {
        $h=($nn[4]=="")?"00":$nn[4];
        $i=($nn[5]=="")?"00":$nn[5];
        $s=($nn[6]=="")?"00":$nn[6];
        $result = "{$nn[3]}-{$nn[2]}-{$nn[1]} {$h}:{$i}:{$s}";
    } elseif (preg_match("/(?:([0-9]{2,4})(?:\-|\.|年|\/|\\\))?(?:([0-9]{1,2})(?:\-|\.|月|\/|\\\))?(?:([0-9]{1,2})(?:\s|日|$))?/", $str, $nn)) {
        $result = ((strlen($nn[1]) == 2) ? "20" . $nn[1] : $nn[1]) . "-" . buqi($nn[2]) . "-" . buqi($nn[3]);
    }
    $result = preg_replace("/\-\-/", "-" . date("m") . "-", $result);
    $result = preg_replace("/\-(\s|$)/", "-" . date("d"), $result);
    $result = preg_replace("/^\-/", date("Y") . "-", $result);

    if (!preg_match("/[0-9]{4}\-[0-9]{2}\-[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}/", $result)) {
        if (preg_match("/([0-9]{1,2})(?:\:|时|$|点)(?:([0-9]{1,2})(?:\:|分|$))?(?:([0-9]{1,2}))?/", $str, $nn)) {
            if ($nn[1] <= 23 && ($nn[2] <= 59 || $nn[2] == "") && ($nn[3] <= 59 || $nn[3] == "")) {
                $result .= " " . buqi($nn[1]) . ":" . buqi($nn[2]) . ":" . buqi($nn[3]);
            } else {
                $result .= " 00:00:00";
            }
        }
    }
    $result = preg_replace("/\:\:/", ":00:", $result);
    $result = preg_replace("/\:$/", ":00", $result);
    $result = preg_replace("/^-/", date("Y") . "-", $result);
    if (strtotime($result) == "") $result = date("Y-m-d H:i:s");
    return $result;
}
//function str2time($str){
//    $str=trim($str);
//    if(preg_match("/^[0-9]+$/",$str)) return $str;
//    if(preg_match("/([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2}?)(?:\s+(?:\s*([0-9]{1,2}?)\s*(?:\:\s*([0-9]{1,2}?))??(?:\:([0-9]{1,2}?))??)??)??/Uisx",$str,$nn)){
//        for($i=2;$i<=6;$i++) $nn[$i]=(strlen($nn[$i])==1)?"0".$nn[$i]:$nn[$i];
//        for($i=2;$i<=6;$i++) $nn[$i]=(trim($nn[$i])=="")?"00":$nn[$i];
//        $str=$nn[1]."-".$nn[2]."-".$nn[3]." ".$nn[4].":".$nn[5].":".$nn[6];
//    }
//    return mktime(substr($str,11,2),substr($str,14,2),substr($str,17,2),substr($str,5,2),substr($str,8,2),substr($str,0,4));
//}

function buqi($s){
    return (strlen($s)==1)?"0".$s:$s;
}

function toarraystr($arr){
    $arr=array_values($arr);
    $s="";
    for($i=0;$i<count($arr);$i++){
        $s.=$arr[$i].",";
    }
    return "[".substr($s,0,-1)."]";
}

function toarraystr2($arr){
    $arr=array_values($arr);
    $s="";
    for($i=1;$i<=count($arr);$i++){
        $s.="[{$i},{$arr[$i-1]}],";
    }
    return "[".substr($s,0,-1)."]";
}

if(!function_exists('str2time')) {
    function str2time($str)
    {
        $str = trim($str);
        if($str=="") return "";
        if (preg_match("/^[0-9]+$/", $str)) return $str;
        if (preg_match("/([0-9]{4})\-([0-9]{1,2})\-([0-9]{1,2}?)(?:\s+(?:\s*([0-9]{1,2}?)\s*(?:\:\s*([0-9]{1,2}?))??(?:\:([0-9]{1,2}?))??)??)??/Uisx", $str, $nn)) {
            for ($i = 2; $i <= 6; $i++) $nn[$i] = (strlen($nn[$i]) == 1) ? "0" . $nn[$i] : $nn[$i];
            for ($i = 2; $i <= 6; $i++) $nn[$i] = (trim($nn[$i]) == "") ? "00" : $nn[$i];
            $str = $nn[1] . "-" . $nn[2] . "-" . $nn[3] . " " . $nn[4] . ":" . $nn[5] . ":" . $nn[6];
        }
        return mktime(substr($str, 11, 2), substr($str, 14, 2), substr($str, 17, 2), substr($str, 5, 2), substr($str, 8, 2), substr($str, 0, 4));
    }
}

function u2($text)
{
    $ew = mb_detect_encoding($text, "UTF-8, ISO-8859-1,GB2312, GBK");
    if($ew=="UTF-8") {
        return $text;
    }else{
        $text = iconv("GB2312", "UTF-8//IGNORE", $text);
    }

    return $text;
}

function g2($text)
{
    $text = iconv("UTF-8", "GB2312//IGNORE", $text);
    return $text;
}


function array_vals($arr, $key = null)
{
    $newarr = array();
    for ($i = 0; $i < count($arr); $i++) {
        if (is_string($key)) {
            $newarr[] = $arr[$i][$key];
        } elseif (is_array($key)) {
            foreach ($arr[$i] as $k => $v) {
                if (is_int($k) || !in_array($k, $key)) unset($arr[$i][$k]);
            }
            $newarr[] = $arr[$i];
        } elseif ($key == null) {
            foreach ($arr[$i] as $k => $v) {
                if (is_int($k)) unset($arr[$i][$k]);
            }
            $newarr[] = $arr[$i];
        }
    }
    return $newarr;
}


function zhiduan($dbname, $tablename)
{
    global $cn, $tablekey;
    $sql = "SELECT * FROM information_schema.columns WHERE table_schema = '$dbname' AND table_name = '$tablename'";
//echo $sql;  
    $ku = mysqli_query($cn, $sql);
    $arr = array();
    while ($r = mysqli_fetch_array($ku)) {
        $arr[$r['COLUMN_NAME']]['type'] = $r['DATA_TYPE'];
        $arr[$r['COLUMN_NAME']]['column_type'] = $r['COLUMN_TYPE'];
        $arr[$r['COLUMN_NAME']]['len'] = $r['CHARACTER_MAXIMUM_LENGTH'];
        $arr[$r['COLUMN_NAME']]['comment'] = $r['COLUMN_COMMENT'];
        $arr[$r['COLUMN_NAME']]['default'] = $r['COLUMN_DEFAULT'];
        preg_match("/^(.*)\[.*\]/", $r['COLUMN_COMMENT'], $nn);
        if ($nn[1] != "") {
            $arr[$r['COLUMN_NAME']]['va'] = va($r['COLUMN_COMMENT']);
        } else {
            $arr[$r['COLUMN_NAME']]['va'] = array();
        }
        $arr[$r['COLUMN_NAME']]['flags'] = $r['COLUMN_KEY'];
        $arr[$r['COLUMN_NAME']]['null'] = $r['IS_NULLABLE'];
        $arr[$r['COLUMN_NAME']]['px'] = $arr[$i]['va']['px'] ? $arr[$i]['va']['px'] : 99;
        $arr[$r['COLUMN_NAME']]['px'] = $arr[$i]['va']['sort'] ? $arr[$i]['va']['sort'] : $arr[$i]['px'];
        if ($arr[$r['COLUMN_NAME']]['flags'] == "PRI") {
            $tablekey = $r['COLUMN_NAME'];
        }
    }

    return $arr;
}

function tableinfo($dbname,$tablename){
	return getrow("SHOW TABLE STATUS WHERE `NAME`='{$tablename}'");
}

function va($str)
{
//name[width:45,height:a=32|b=5]    
    $va = array();
    preg_match("/\[(.*)\]/", $str, $nn);
    $va['name'] = str_replace($nn[0], "", $str);
    $str = $nn[1];
    $nn = explode(",", $str);
    for ($i = 0; $i < count($nn); $i++) {
        $n = explode_once(":", $nn[$i]);
        $name = $n[0];
        if (trim($name) == "") continue;
        if (preg_match("/\|/", $n[1])) {
            $n2 = explode("|", $n[1]);
            for ($j = 0; $j < count($n2); $j++) {
                $n3 = explode("=", $n2[$j]);
                $va[$name][$n3[0]] = ($n3[1] == "") ? $n3[0] : $n3[1];
            }
        } else {
            $value = $n[1];
            $va[$name] = ($value == "") ? 1 : $value;
        }
    }
    return $va;
}

function clzw($str)
{
    $str = preg_replace("/\s+/", "", trim(strip_tags($str,"<p><img><table><tr><td><br><b><strong>")));
    return $str;
}

if(!function_exists('re')){
function re($re, $tempnr = "")
{
    $tempnr = preg_replace("/<meta[^<>]+charset=[^<>]*>/Uisx", "", $tempnr);
    $tempnr = preg_replace_callback("/<head[^<>]*>(.*)<\/head>/Uisx", function($em){
        $em[1]=preg_replace("/<meta[^<>]*charset[^<>]*>.*<\/meta>/Uisx","",$em[1]);
        return "<head>{$em[1]}</head>";
    }, $tempnr);
    $tempnr = preg_replace("/<\/head>/Uisx", "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\r\n</head>", trim($tempnr));
    if(!preg_match("/^(\.|\#)/",$re)) {
        if (preg_match("/&&&/", $re)) {
            $tmpre = preg_match("/^(.*)\&\&\&(.*)$/Uisx", $re, $nn);
            preg_match("/$nn[1]/Uisx", $tempnr, $nn2);
            $tempnr2 = $nn2[1];
            $re = $nn[2];
            preg_match_all("/$re/Uisx", $tempnr2, $nn);
            $result = $nn[0][0];
        } else {
            preg_match_all("/$re/Uisx", $tempnr, $nn);
            $result = $nn[1][0];
        }
    }else{
        $pqy2=phpQuery::newDocumentHTML($tempnr);
        $rej = preg_replace("/(->|\:add|\:nn[0-9]).*$/", "", $re);
        $aSstrs = pq($rej,$pqy2);
        if(count($aSstrs->elements)>1) {
            foreach ($aSstrs->elements as $li2) {
                if (preg_match("/->(.*)(\:nn[0-9]+|$)/Uisx", $re, $nnexe)) {
                    $str = "\$temp=pq(\$li2)->" . $nnexe[1];
                    $fn = fopen("includetemp.php", "w");
                    fwrite($fn, "<" . "?php\r\n" . $str . "\r\n?" . ">");
                    fclose($fn);
                    include("includetemp.php");
                    if (!is_string($temp)) {
                        $result[] = pq($temp)->htmlOuter();
                    }else{
                        $result[] = $temp;
                    }
                }
            }
        }else{
            if (preg_match("/->(.*)(\:nn[0-9]+|$)/Uisx", $rej, $nnexe)) {
                $str = "\$temp=pq(\$li2)->" . $nnexe[1];
                $fn = fopen("includetemp.php", "w");
                fwrite($fn, "<" . "?php\r\n" . $str . "\r\n?" . ">");
                fclose($fn);
                include("includetemp.php");
                if (!is_string($temp)) {
                    $result[] = pq($temp)->htmlOuter();
                }else{
                    $result[] = $temp;
                }
            }else{
                $result=pq($aSstrs)->htmlOuter();
            }
        }
    }
    return $result;
}
}

if(!function_exists('msubstr2')){
    function msubstr2($str, $start=0, $length, $charset="utf-8", $suffix=true) {
        if(strlen($str) > $length) {
            if(function_exists("mb_substr"))
                $slice = mb_substr($str, $start, $length, $charset);
            elseif(function_exists('iconv_substr')) {
                $slice = iconv_substr($str,$start,$length,$charset);
                if(false === $slice) {
                    $slice = '';
                }
            }else{
                $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
                $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
                $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
                $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
                preg_match_all($re[$charset], $str, $match);
                $slice = join("",array_slice($match[0], $start, $length));
            }
            return $suffix ? $slice.'...' : $slice;
        }
        return $str;
    }
}

if(!function_exists('clwz')){
function clwz($str)
{
    $str = trim(strip_tags($str,"<p><br><b><img><strong>"));
    $str=preg_replace("/\s(class|style)\s*=\s*\"[^<>]*\"/Uisx","",$str);
    $str=preg_replace("/data-src/Uisx","src",$str);
    $str=preg_replace("/\sdata\-[^<>\s]+\s*=\s*\"[^<>]*\"/Uisx","",$str);
    return $str;
}
}


function http($poststr){
    return curlpost($poststr);
}
function curlpost($poststr,$header=0){
    preg_match("/^(?:get|post)\s+([^\s]*)\s+HTTP/Uisx",$poststr,$nn);
    $url=$nn[1];
    preg_match("/^((?:post|get)\s+?(?:.*))(?:\r\n\r\n|\n\n)(.+?)$/Uis", $poststr, $nn);
    $Header=$nn[1];
    $Querystring=trim($nn[2]);
    preg_match("/^Cookie\:\s*([^\s]+?)\s*$/Uism", $poststr, $nn);
    $Cookie=trim($nn[1]);
    $Cookie=preg_replace("/(XDEBUG_SESSION_START|PHPSESSID)=[^\;\s]*;?/i","",$Cookie);
    preg_match_all("/^(?!post|get|Accept-encoding|Content-Length|Cookie)(.*)$/Uimx",$Header,$nn);
    $headers=array();
    for($i=0;$i<count($nn[1]);$i++){
        $nn[1][$i]=trim($nn[1][$i]);
        if($nn[1][$i]!="") $headers[]=trim($nn[1][$i]);
    }
    $headers[]="Content-Length: ".strlen($Querystring);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36");
    //curl_setopt($ch, CURLOPT_COOKIE,"Hm_lvt_3b1e939f6e789219d8629de8a519eab9=1717149957; Hm_lpvt_3b1e939f6e789219d8629de8a519eab9=1717950648");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, "false");
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, "2");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,0);
    curl_setopt($ch, CURLOPT_VERBOSE,1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_POST, true );
    curl_setopt($ch, CURLOPT_POSTFIELDS, trim($Querystring));
    curl_setopt($ch, CURLOPT_COOKIE,$Cookie);
    $r=curl_exec($ch);
    curl_close($ch);
    return $r;
}

function array_utf8($data)
{
    if (empty($data)) {
        return $data;
    }
    return is_array($data) ? array_map('array_utf8', $data) : iconv("GBK","UTF-8",$data);
}

function array_gbk($data)
{
    if (empty($data)) {
        return $data;
    }
    return is_array($data) ? array_map('array_gbk', $data) : iconv("UTF-8","GBK",$data);
}

function curl_file_get_contents_api($url,$method="get",$data,$header=0,$cookie="",$httpheader=array("Content-Type: application/x-www-form-urlencoded")){
    $cookie=preg_replace("/Cookie\:/i","",$cookie);
    if(is_string($httpheader)) {
        $httpheader = strtohttpheader($httpheader, $cookie);
    }elseif($cookie!="") {
        $httpheader[] = "Cookie: " . trim(preg_replace("/^cookie\:/Uisx", "", $cookie));
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0');
    curl_setopt($ch, CURLOPT_HEADER, $header);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    //curl_setopt( $ch, CURLOPT_COOKIE, $cookie);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, $httpheader);
    if($httpheader!="") {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
    }

    if(strtolower($method)=="post"||!empty($data)) {
        curl_setopt($ch, CURLOPT_POST, true );
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, Content_Length, strlen($data));
    }
    curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
    $result=curl_exec($ch);
    //echo $url;exit;
    //echo $result;
    $request_header = curl_getinfo($ch, CURLINFO_HEADER_OUT).$data;
    //echo $request_header;exit;
    curl_close($ch);
    return $result;
}

function strtohttpheader($str,$cookie){
    preg_match_all("/^([^\r\n\s\"\'\[\{]*)\:([^\r\n]*)\s*$/im",$str,$nn);
    $result=array();
    for($i=0;$i<count($nn[0]);$i++){
        if(!preg_match("/^Cookie|Accept\-Encoding|Referer/Uisx",$nn[1][$i])&&trim($nn[0][$i])!="") {
            $result[] = trim($nn[0][$i]);
        }
    }
    if($cookie!="") {
        $result[] = "Cookie: " . preg_replace("/^cookie\:/Uisx", "", trim($cookie));
    }
    return $result;
}


function file_get_contents2($url,$data=null,$header=null){
    if(file_exists("10000.html")){
        $nr=file_get_contents("10000.html");
        if($nr!=""){
            return $nr;
        }
    }
    if($data==null) {
        preg_match("/(http.*)\?(.*)$/Uisx", $url, $hh);
        $url = $hh[1];
        $header=($header==null)?"Content-type:application/x-www-form-urlencoded;":$header;
        $option = array(
            'http' => array(
                'method' => 'GET',
                'header' => $header,
                'content' => "{$hh[2]}",
            ),
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
            )
        );
    }else{
        $option = array(
            'http' => array(
                'method' => 'POST',
                'header' => $header,
                'content' => $data,
            ),
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
            )
        );

    }

    $context = stream_context_create($option);
    $content = file_get_contents("{$url}",false,$context);

    if($content!="") {
        file_put_contents("10000.html",$content);
    }
    return $content;
}

function element2($url, $stopstr = ".video",$rand="")
{
    if (strlen(trim($url)) < 2) {
        return "";
    }
    $clickstr = ".player";
    $stopstr2 = ".video";
    $timee = 1;
    $stopiframe = ($stopiframe == "") ? "None" : ceil($stopiframe);
    $clickiframe = ($clickiframe == "") ? "None" : ceil($clickiframe);
    if($rand==""){
        $rand=rand(100000,999999);
    }elseif(file_exists($rand.".html")){
        $nr=file_get_contents($rand.".html");
        if($nr!=""){
            return $nr;
        }
    }
    $curl = curl_init();
    $host = host($url);
    $cmd = "$url $host $stopstr $clickstr $stopstr2 $timee $stopiframe $clickiframe $rand 0";
    $url = 'http://120.77.245.205/python/getelement.php?url=' . urlencode($url) . '&stopstr=' . urlencode($stopstr) . '&clickstr=' . urlencode($clickstr) . '&stopstr2=' . urlencode($stopstr2) . "&timee=" . $timee."&stopiframe={$stopiframe}&clickiframe={$clickiframe}&rand={$rand}&r=".rand(100000,999999);
    //$url = 'https://www.baidu.com/';
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0");
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt($curl, CURLOPT_TIMEOUT, 35);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    ini_set('display_errors', 'On');
    if(($data =curl_exec($curl)) === ""){
        $httphead=curl_getinfo( $curl,CURLINFO_HEADER_OUT);
        header('Curl error: ' . curl_error($curl).$httphead);
    }else {
        header('Curl:' . curl_error($curl) . $httphead);
    }
    curl_close($curl);
    if($data!="") {
        file_put_contents("{$rand}.html",$data);
    }
    return $data;
}
//排版与美化HTML
function htmlnice($code){
    include($_SERVER['DOCUMENT_ROOT']."/collect/Lib/dindent/src/Exception/DindentException.php");
    include($_SERVER['DOCUMENT_ROOT']."/collect/Lib/dindent/src/Exception/InvalidArgumentException.php");
    include($_SERVER['DOCUMENT_ROOT']."/collect/Lib/dindent/src/Exception/RuntimeException.php");
    include($_SERVER['DOCUMENT_ROOT']."/collect/Lib/dindent/src/Indenter.php");
    try {
        $indenter = new \Gajus\Dindent\Indenter();
        $result = @$indenter->indent($code);
    }catch(Exception $exception) {
        return $code;
    }
    return $result;
}

function curlhttpheader($httpheader,$header=0){
    $str=$httpheader;
    if(preg_match("/^Post|get/i",$httpheader)){
        preg_match("/(POST|GET)\s+([^\s]*)\s+HTTP/Uisx",$str,$nn);
        $ispost=(strtoupper($nn[1])=="POST")?true:false;
        $durl=$nn[2];
        preg_match("/Referer\:\s*([^\n]*)$/ixm",$str,$nn);
        $Referer=$nn[1];
        preg_match("/Cookie\:\s*([^\n]*)$/ixm",$str,$nn);
        $cookie=$nn[1];
        preg_match("/(^.*)(?:\r\n\r\n|\n\n)(.*?)$/Uis", $str, $nn);
        $postdata = trim($nn[2]);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $durl);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, "false");
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, "2");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        if ($Referer != "" && $Referer != "http://") {
            curl_setopt($ch, CURLOPT_REFERER, $Referer);
        }
        if ($cookie != "") {
            curl_setopt($ch, CURLOPT_COOKIE, trim($cookie));
        }
        if ($ispost) {
            curl_setopt( $ch, CURLOPT_POST, true );
            curl_setopt( $ch, CURLOPT_POSTFIELDS, $postdata);
        }

        $heads=guolvpoststr($str,$postdata);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $heads);
        curl_setopt($ch, CURLOPT_HEADER, $header);
        curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
        $html = curl_exec($ch);
        return  $html;
    }
}

if(!function_exists("guolvpoststr")) {
    function guolvpoststr($str, $postdata)
    {
        preg_match_all("/^(.*)\:(.*)$/Uimx", $str, $nn);
        $data['httpheader'] = array();
        for ($i = 0; $i < count($nn[1]); $i++) {
            if (!in_array($nn[1][$i], array("Cookie", "Host", "Referer", "Content-Length", "Referer", "RETURNTRANSFER", "X-FORWARDED-FOR", "SSL-VERIFYHOST", "SSL-VERIFYPEER", "SSL-VERIFYHOST", "Accept-Language", "Accept-Encoding"))) {
                if (!preg_match("/(GET|POST)\s/i", $nn[1][$i])) {
                    $data['httpheader'][] = "{$nn[1][$i]}:" . trim($nn[2][$i]) . "";
                }
            }
        }
        $data['httpheader'][] = "Content-Length:" . strlen(trim($postdata)) . "";
        return $data['httpheader'];
    }
}


function postCookie($host,$cookie){
    $urls=array(
        "http://collect1.longsunhd.com:1013/collect/setCookies.php",
        "http://collect.longsunhd.com/collect/setCookies.php",
        "http://collect34.longsunhd.com/collect/setCookies.php",
        "http://120.77.245.205/python/setcookie.php"
    );
    $data=array("host"=>$host,"cookie"=>$cookie);
    for($i=0;$i<count($urls);$i++) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $urls[$i]);
        curl_setopt($ch, CURLOPT_REFERER, $urls[$i]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0');
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $result = curl_exec($ch);
        curl_close($ch);
    }

}

function zhiduan_text($dbname,$tablename){
    global $g;
    $nn=explode(",",$tablename);
    for($i=0;$i<count($nn);$i++) {
        $arr = zhiduan($dbname, $nn[$i]);
        $tbn = preg_replace("/^.*_/", "", $nn[$i]);
        echo "//{$nn[$i]}表：\r\n";
        foreach ($arr as $k => $v) {
            $n=54-strlen($k.$tbn);
            if($v['comment']!=""){
                tofanyi($k,$v['comment']);
            }else{
                $v['comment']=fanyi($k,$tbn);
            }
            echo "\$_{$tbn}['{$k}']".str_repeat(" ",$n)."//{$v['comment']}\r\n";
            $g[]=array("k"=>$k,"v"=>"\$_{$tbn}['{$k}']","c"=>$v['comment']);
        }
    }
}

function fanyiyangjc($q,$to="cn"){
    $from=$to=="cn"?"en":"cn";
    $q=strtolower(trim($q));
    $result=getone("select $to from jipu.jipu_fanyi where $from='$q'");
    if($result!="0"){
        return $result;
    }else {
        $context = stream_context_create(array(
            'http' => array(
                'timeout' => 3000, // 设置超时时间，单位为秒
            )
        ));
        $n=0;
        while(($result==""||$result=="0")&&$n++<10){
            $result = file_get_contents("http://fanyi.yangjc.com/?q={$q}&to={$to}", false, $context);;
        }
        $result=strtolower(trim($result));
        $data=array();
        if($to=="cn"){
            $data["cn"]=$result;
            $data["en"]=$q;
            insertupdate("jipu.jipu_fanyi",$data,"select id from jipu.jipu_fanyi where en={$data["en"]}");
        }else{
            $data["cn"]=$q;
            $data["en"]=$result;
            insertupdate("jipu.jipu_fanyi",$data,"select id from jipu.jipu_fanyi where cn={$data["cn"]}");
        }

    }
    return $result;
}
function fanyi($w,$tbn){
    global $g;
    if(preg_match("/(.*)([0-9]+)/",$w,$nn)){
        return fanyi($nn[1],$tbn).$nn[2];
    }
    $r=getone("select value from longzs.fanyi where `key`='$w'");
    $result="";
    if($r==null&&$w!=""){
        $result = @system("python D:\\website\\word.longsunhd.com\\python\\fanyi.py $w");
        $data=array();
        $data['key']=$w;
        $data['value']=$result;
        if($data['value']!="") {
            insertupdate("longzs.fanyi", $data, "select id from longzs.fanyi where `key`='$w'");
        }
    }else{
        $result=$r;
    }
    if(preg_match_all("/(.*)_/",$w,$nn)){
        $result.=" ";
        for($i2=0;$i2<count($nn[1]);$i2++) {
            if($nn[1][$i2]!=$w) {
                $c=fanyi($nn[1][$i2],$tbn);
                $result.= $c;
                $g[]=g_add($nn[1][$i2],$tbn,$c);
            }
        }
        $k=preg_replace("/^.*_/","",$w);
        $c=fanyi($k,$tbn);
        $result.=$c;
        g_add($k,$tbn,$c);
        return $result;
    }
    if(preg_match_all("/([A-Z][a-z]+)/",$w,$nn)){
        $result.=" ";
        $k=preg_replace("/[A-Z].*$/","",$w);
        $c=fanyi($k,$tbn);
        $result.=$c;
        g_add($k,$tbn,$c);
        for($ii=0;$ii<count($nn[1]);$ii++){
            if($nn[1][$ii]!=$w){
                $c=fanyi($nn[1][$ii],$tbn);
                $result.= $c;
                g_add($k,$tbn,$c);
            }
        }
        return $result;
    }
    return $result;
}

function g_add($k,$tbn,$c){
    global $g;
    if(!in_array($k,array_column($g,'v'))) {
        //$g[] = array("k" => $k, "v" => "\$_{$tbn}['{$k}']", "c" => $c);
    }
}

function tofanyi($w,$result){
    $data=array();
    $data['key']=$w;
    $data['value']=$result;
    if($data['value']!="") {
        insertupdate("longzs.fanyi", $data, "select id from longzs.fanyi where `key`='$w'");
    }
}

function readK($data,$name=""){
    global $g,$desc,$settableKey,$searchRe;
    if(is_array($data)&&!empty($data[0])){
        for($i=0;$i<count($data);$i++){
            readK($data[$i],$name,1);
        }
    }else{
        foreach($data as $k=>$v){
            $namek = $name != "" ? "{$name}" : "";
            if(is_array($v)) {
                echo "\n\$_{$k}=query(\"select * from li_order where id=1\");\r\n";
                readK($v,$k,0);
            }else{
                $n=50-strlen($k.$namek);
                $bz=fanyi($k,$namek);
                $vs=similar($k,$bz,$namek);
                $vsn=preg_replace("/[\r\n]/","",$vs);
                echo "\${$namek}['{$k}']=\"\";".str_repeat(" ",$n)."//{$bz} 值如：{$v} {$vsn} {$desc[$k]}\r\n";
            }
            $data=array();
            $data['arrayk']="\${$namek}['{$k}']";
            $data['comment']="{$bz} {$desc[$k]} 值如：{$v}";
            $data['options']=preg_replace("/^\s*|\s*$/m","",$vs);
            $data['opt']=$settableKey;
            $data['required']=preg_match("/必填|强制|必选|必须/",$data['comment'])?"必填":"";
            $wherev=str_replace("'","\'",$data['arrayk']);
            insertupdate("longzs.fanyi_set",$data,"select id from longzs.fanyi_set where opt='{$settableKey}' and arrayk='{$wherev}'");
        }
    }
}

function similar($k,$bz,$namek){
    global $g,$searchRe;
    $result="";
    $index=array();
    $is1=$is2=1;
    $splits=explode("_",$k);
    $splits_cn=array_unique(explode(" ",$bz));
    if(preg_match("/[A-Z]/",$k)) {
        preg_match_all("/([A-Z][a-z]*)/", $k, $nn);
        for ($i = 0; $i < count($nn[1]); $i++) {
            $splits[] = $nn[$i][$i];
        }
        $splits[] = preg_replace("/^(.*)[A-Z].*$/", "\\1", $k);
    }
    $searchxxx=$searchRe["\${$namek}['{$k}']"];
    for($i=0;$i<count($g);$i++){
        $index[$i]=0;
        //变量名称相同
        $key=$g[$i]['k'];
        $cn=$g[$i]['c'];
        if($key==$k){
            $index[$i]=$index[$i] + 5;
        }

        //分割变量名存在，多少个加多少次
        for($j=0;$j<count($splits);$j++){
            if($key==$splits[$j]){
                $index[$i]=$index[$i] + 1;
            }
        }

        similar_text($key,$k,$per);
        if($per>80) $index[$i]++;

        for($j2=0;$j2<count($splits_cn);$j2++) {
            similar_text($cn, $splits_cn[$j2], $per);
            if ($per > 50) {
                $index[$i]=$index[$i] + 5;
            }
        }

        //上层变量名称存在
        preg_match("/\\\$_(.*)\[/", $g[$i]['v'], $nn);
        $tbn = $nn[1];
        $tbncn = fanyi($tbn, $tbn);
        if ($tbn != "" && stristr($k, $tbn)) {
            $index[$i]=$index[$i] + 1;
        }

        if($searchxxx!=""){
            $mm=explode("|",$searchxxx);
            for($i3=0;$i3<count($mm);$i3++){
                if(stristr($cn,$mm[$i3])){
                    $index[$i]=$index[$i] + 5;
                }
                if(stristr($key,$mm[$i3])){
                    $index[$i]=$index[$i] + 5;
                }
            }
        }


    }
    arsort($index);
    foreach($index as $k=>$v) {
        if ($v >= 1) $result .= " " . $g[$k]['v'] . ":{$g[$k]['c']} \n";
    }
    return $result;
}

function description($description){
    $result=array();
    preg_match_all("/^([a-zA-Z0-9_]+)(.*)$/imx",$description,$lines);
    for($i=0;$i<count($lines[0]);$i++) {
        $result[$lines[1][$i]]=$lines[2][$i];
    }
    return $result;
}

function searchRe(){
    global $settableKey,$searchRe;
    $rs=query("select *  from longzs.fanyi_set where opt='{$settableKey}'");
    for($i=0;$i<count($rs);$i++) {
        $searchRe[$rs[$i]['arrayk']] = $rs[$i]['seachre'];
    }
    return $searchRe;
}

function getJsonReByHost($host){
    $rs=query("select re from longzs.longzs_re where host='{$host}'");
    $re=$rs[0]['re'];
    preg_match_all("/^([^\r\n]+)\:tojsdata/Uisx",$re,$nn);
    $s="";
    for($i=0;$i<count($nn[1]);$i++){
       $s.=trim($nn[0][$i])."\r\n";
    }
    return trim($s);
}


function createID()
{
    //假设一个机器id
    $machineId = 1234567890123456897;

    //41bit timestamp(毫秒)
    $time = floor(microtime(true) * 1000);

    //0bit 未使用
    $suffix = 0;

    //datacenterId  添加数据的时间
    $base = decbin(pow(2, 40) - 1 + $time);

    //workerId  机器ID
    $machineid = decbin(pow(2, 9) - 1 + $machineId);

    //毫秒类的计数
    $random = mt_rand(1, pow(2, 11) - 1);

    $random = decbin(pow(2, 11) - 1 + $random);
    //拼装所有数据
    $base64 = $suffix . $base . $machineid . $random;
    //将二进制转换int
    $base64 = bindec($base64);

    $id = sprintf('%.0f', $base64);

    return $id;
}

function str_replaces($a,$b,$c){
    if(preg_match("/{$a}/",$c)){
        return str_replace($a,$b,$c);
    }else{
        return "";
    }
}


/**
 * 雪花算法类  SnowFlake.generateParticle()
 * @package app\helpers
 */
class SnowFlake
{
    const EPOCH = 1479533469598;
    const max12bit = 4095;
    const max41bit = 1099511627775;

    static $machineId = null;

    public static function machineId($mId = 0)
    {
        self::$machineId = $mId;
    }

    public static function generateParticle()
    {
        /*
        * Time - 42 bits
        */
        $time = floor(microtime(true) * 1000);

        /*
        * Substract custom epoch from current time
        */
        $time -= self::EPOCH;

        /*
        * Create a base and add time to it
        */
        $base = decbin(self::max41bit + $time);


        /*
        * Configured machine id - 10 bits - up to 1024 machines
        */
        if (!self::$machineId) {
            $machineid = self::$machineId;
        } else {
            $machineid = str_pad(decbin(self::$machineId), 10, "0", STR_PAD_LEFT);
        }

        /*
        * sequence number - 12 bits - up to 4096 random numbers per machine
        */
        $random = str_pad(decbin(mt_rand(0, self::max12bit)), 12, "0", STR_PAD_LEFT);

        /*
        * Pack
        */
        $base = $base . $machineid . $random;

        /*
        * Return unique time id no
        */
        return bindec($base);
    }

    public static function timeFromParticle($particle)
    {
        /*
        * Return time
        */
        return bindec(substr(decbin($particle), 0, 41)) - self::max41bit + self::EPOCH;
    }
}

function getCidName($id){
    return getone("SELECT `name` FROM jipu.`jipu_item_category` WHERE id={$id}");
}

/**
 * 补充字段
 * @param $data
 * @param $paichustr
 * @return void
 */
function buchongzhiduan($data,$paichustr){
    $pcarr=explode(",",$paichustr);
    $result=array();
    $mbdata=query("SELECT COLUMN_COMMENT,COLUMN_NAME,DATA_TYPE,COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'jipu'  AND TABLE_NAME = 'jipu_item'");
    $temphtml="";
    for($i=0;$i<count($mbdata);$i++){
        if(in_array($mbdata[$i]['COLUMN_NAME'],$pcarr)){
            continue;
        }
        $mbdata[$i]['COLUMN_COMMENT']=preg_replace("/\[.*\]/","",$mbdata[$i]['COLUMN_COMMENT']);
        $mbdata[$i]['COLUMN_NAME']=strtolower($mbdata[$i]['COLUMN_NAME']);
        if($mbdata[$i]['DATA_TYPE']=="varchar"){
            $mb="            <div class=\"form-item cf\">
              <label class=\"item-label\">{$mbdata[$i]['COLUMN_COMMENT']}<span class=\"check-tips\"></span></label>
              <div class=\"controls\">
                <input type=\"text\" class=\"text input-mid\" name=\"{$mbdata[$i]['COLUMN_NAME']}\" value=\"{\$data[{$mbdata[$i]['COLUMN_NAME']}] ? \$data[{$mbdata[$i]['COLUMN_NAME']}] : '';}\">
              </div>
            </div>";
            $str="            <div class=\"form-item cf\">
              <label class=\"item-label\">{$mbdata[$i]['COLUMN_COMMENT']}<span class=\"check-tips\"></span></label>
              <div class=\"controls\">
                <input type=\"text\" class=\"text input-mid\" name=\"{$mbdata[$i]['COLUMN_NAME']}\" value=\"{$data[$mbdata[$i]['COLUMN_NAME']]}\">
              </div>
            </div>";
        }elseif($mbdata[$i]['DATA_TYPE']=="int"||$mbdata[$i]['DATA_TYPE']=="smallint"||$mbdata[$i]['DATA_TYPE']=="tinyint"){
            $mb="            <div class=\"form-item cf\">
              <label class=\"item-label\">{$mbdata[$i]['COLUMN_COMMENT']}<span class=\"check-tips\"></span></label>
              <div class=\"controls\">
                <input type=\"text\" class=\"text input-mid\" name=\"{$mbdata[$i]['COLUMN_NAME']}\" value=\"{\$data[{$mbdata[$i]['COLUMN_NAME']}] ? \$data[{$mbdata[$i]['COLUMN_NAME']}] : ''}\">
              </div>
            </div>";
            $str="            <div class=\"form-item cf\">
              <label class=\"item-label\">{$mbdata[$i]['COLUMN_COMMENT']}<span class=\"check-tips\"></span></label>
              <div class=\"controls\">
                <input type=\"text\" class=\"text input-mid\" name=\"{$mbdata[$i]['COLUMN_NAME']}\" value=\"{$data[$mbdata[$i]['COLUMN_NAME']]}\">
              </div>
            </div>";
        }elseif($mbdata[$i]['DATA_TYPE']=="text"){
            $mb="            <div class=\"form-item cf\">
              <label class=\"item-label\">{$mbdata[$i]['COLUMN_COMMENT']}<span class=\"check-tips\"></span></label>
              <div class=\"controls\">
                <textarea class=\"text input-mid\" name=\"{$mbdata[$i]['COLUMN_NAME']}\"  id=\"{$mbdata[$i]['COLUMN_NAME']}\" placeholder=\"{$mbdata[$i]['COLUMN_COMMENT']}\" style=\"padding-left:10px;width:90%;height:20px\">{\$data['{$mbdata[$i]['COLUMN_NAME']}'] ? \$data['{$mbdata[$i]['COLUMN_NAME']}'] : ''}</textarea>
              </div>
            </div>";
            $str="            <div class=\"form-item cf\">
              <label class=\"item-label\">{$mbdata[$i]['COLUMN_COMMENT']}<span class=\"check-tips\"></span></label>
              <div class=\"controls\">
                <textarea class=\"text input-mid\" name=\"{$mbdata[$i]['COLUMN_NAME']}\"  id=\"{$mbdata[$i]['COLUMN_NAME']}\" placeholder=\"{$mbdata[$i]['COLUMN_COMMENT']}\" style=\"padding-left:10px;width:90%;height:20px\">{$data[$mbdata[$i]['COLUMN_NAME']]}</textarea>
              </div>
            </div>";
        }
        $result[]=$data[$i];
        $temphtml.=$str."\n";
    }
    return $temphtml;
}

function searchArray($data,$tiaojian,$resultstr){
    $result=array();
    for($i=0;$i<count($data);$i++){
        foreach ($tiaojian as $k => $value) {
            if (array_key_exists($k, $data[$i])&&$data[$i][$k]==$value) {
                $result[]=$data[$i][$resultstr];
            }
        }
    }
    if(count($tiaojian)==1){
        return current($result);
    }
    return $result;
}

function souji(&$data,$v,$str,$ptname="alibaba1688",$arrsku=""){
    $fieldnames=explode(",",$str);
    $pinyin = new Pinyin();
        if($v[$fieldnames[0]]!=null&&is_string($v[$fieldnames[0]])){
            for($i=0;$i<count($fieldnames);$i++) {
                $data[$fieldnames[$i]] = $v[$fieldnames[$i]];
                $fieldname=getone("SHOW COLUMNS FROM jipu.jipu_item LIKE '{$fieldnames[$i]}'");
                if($fieldname=="0"){
                    if(is_int($v[$fieldnames[$i]])){
                        $type="int";
                    }elseif(is_string($v[$fieldnames[$i]])){
                        if(strlen($v[$fieldnames[$i]])>255){
                            $type="text";
                        }else{
                            $type="VARCHAR(255)";
                        }
                    }elseif(is_double($v[$fieldnames[$i]])){
                        $type="decimal(8,2)";
                    }elseif(strtolower($v[$fieldnames[$i]])=="true"||strtolower($v[$fieldnames[$i]])=="false"){
                        $type="bool";
                    }
                    $row=getrow("select * from jipu.jipu_item_ptfield where {$ptname}='{$fieldnames[$i]}'");
                    if($row['id']==null) {
                        $zw = fanyiyangjc($fieldnames[$i]);
                        //query("ALTER TABLE jipu.jipu_item ADD $fieldnames[$i] {$type} COMMENT '{$zw}';");
                        //query("insert into jipu.jipu_item_ptfield (name,shante,$ptname,zwname) value ('{$fieldnames[$i]}','{$fieldnames[$i]}','{$fieldnames[$i]}','{$zw}')");
                    }
                }
                //$data[$fieldnames[$i]]=join(",",$v[$fieldnames[$i]]);
            }
        }elseif(is_array($v)&&is_array($v[0])){
            if($arrsku=="attribute"){
                $str="";
                $index=0;
                for ($i = 0; $i < count($v); $i++) {
                    $data2=array();
                    $ename = fanyiyangjc($v[$i][$fieldnames[0]], "en");
                    $n=0;
                    while($ename==""&&$n++<10){
                          $ename = fanyiyangjc($v[$i][$fieldnames[0]], "en");
                    }
                    $data2['cid']=$data['cid_3'];
                    if($data2['cid']=='0'){
                        $data2['cid']=$data['cid_2'];
                    }
                    $data2['cname']=$v[$i][$fieldnames[0]];
                    $data2['ename']=strtolower($ename);
                    $data2['datatype']='txt';
                    $data2['formtype']='input';
                    $data2['formfillway']="";
                    $data2['formcheck']="";
                    $data2['pic']="";
                    $data2['displayorder']=0;
                    $data2['isrequired']=0;
                    $data2['valuestore']=$v[$i]['value'];
                    $data2['create_time']=time();
                    $data2['update_time']=$data2['create_time'];
                    $data2['is_recommend']=0;
                    $data2['type']="attribute";
                    $data["attribute"][]=$data2;
                    $str.="<div class=\"form-item\">
							<label class=\"item-label\">{$data2['cname']}</label>			<!-- 文本框 -->
					<div class=\"controls\">
						<input type=\"input\" id=\"property-brand-{$index}\" name=\"property[{$index}][{$data2['ename']}]\" class=\"text input-large\" value=\"{$data2['valuestore']}\">
					</div>		</div>";
                    if($data2['cid']!=""&&$data2['cname']!=""&&$data2['ename']!="") {
                        $index++;
                        insertupdate("jipu.jipu_item_property", $data2, "select id from jipu.jipu_item_property where cid='{$data2['cid']}' and ename='{$data2['ename']}' and valuestore='{$data2['valuestore']}'");
                    }
                }
                $data["sku_prp"]=$str;
            }else {
                for ($i = 0; $i < count($v); $i++) {
                    $fieldname = fanyiyangjc($v[$i][$fieldnames[$i]], "en");
                    $zw = $v[$i][$fieldnames[0]];
                    $data[$fieldname] = $v[$i][$fieldnames[1]];
                    $fieldname_temp = getone("SHOW COLUMNS FROM jipu.jipu_item LIKE '{$fieldname}'");
                    if ($fieldname_temp == "0") {
                        if (is_int($v[$i][$fieldnames[1]])) {
                            $type = "int";
                        } elseif (is_string($v[$i][$fieldnames[1]])) {
                            if (strlen($v[$i][$fieldnames[1]]) > 255) {
                                $type = "text";
                            } else {
                                $type = "VARCHAR(255)";
                            }
                        } elseif (is_double($v[$i][$fieldnames[1]])) {
                            $type = "decimal(8,2)";
                        } elseif (strtolower($v[$i][$fieldnames[1]]) == "true" || strtolower($v[$i][$fieldnames[1]]) == "false") {
                            $type = "bool";
                        }
                        $row = getrow("select * from jipu.jipu_item_ptfield where {$ptname}='{$fieldname}'");
                        if ($row['id'] == null) {
                            query("ALTER TABLE jipu.jipu_item ADD $fieldname {$type} COMMENT '{$zw}';");
                            query("insert into jipu.jipu_item_ptfield (name,shante,$ptname,zwname) value ('{$fieldname}','{$fieldname}','{$fieldname}','{$zw}')");
                        }
                    }
                    $data[$fieldname] = $v[$i][$fieldnames[1]];
                }
            }

    }
    return $data;
}



function categorytrees($title,$pttype=1){
    switch ($pttype){
        case 1:
            $table="jipu_item_category";
            break;
        case 2:
            $table="jipu_item_category_dy";
            break;
        case 3:
            $table="jipu_item_category_sph";
            break;
        case 4:
            $table="jipu_item_category_shopee";
            break;
    }
    $sql="SELECT `name` FROM jipu.{$table}";
    $da=query($sql);
    $text="";
    $inarr=array();
    for($i=0;$i<count($da);$i++){
        $r=explode(",",$da[$i]['name']);
        for($j=0;$j<count($r);$j++) {
            if(!in_array(trim($r[$j]),$inarr)&&trim($r[$j])!=""){
                $text .= trim($r[$j]) . "|";
                $inarr[]=trim($r[$j]);
            }
        }
    }
    $text=preg_replace("/\,/","|",$text);
    $text=preg_replace("/\"|\-|\//","",$text);
    $text=preg_replace("/\|$/","",$text);

    //$title="MODIYA厂家直营男表礼品手表批发 watch简约钢带石英男士手表";
    if(preg_match("/([^,\|]*)\.([^,\|]*)/",$text,$nns)){
        $text=preg_replace("/([^,\|]*)\.([^,\|]*)/","\\2",$text);
        $pre=$nns[1];
        $hou=$nns[2];
    }
    $text=preg_replace("/\(|\)/","",$text);
    $ds=explode("|",$text);
    $nn=array();
    $nn[1]=array();
    for($i=0;$i<count($ds);$i++){
        if(strstr($title,$ds[$i])&&strlen($ds[$i])>3){
            $nn[1][]=$ds[$i];
        }
    }
    if(empty($nn[1])) {
        $result[]=array("name"=>"","trees"=>"","str"=>"");
        return $result;
    }else{
        $matchs=array_values(array_unique($nn[1]));
    }
    $result=array();
    for($i=0;$i<count($matchs);$i++) {
        if($matchs[$i]==null) continue;
        $name=$matchs[$i];
        if($name==$hou){
            $name=$pre.".".$hou;
        }
        $data = query("select id,pid,name from jipu.{$table} where name REGEXP '[^\/]*{$name}$'");
        for($j=0;$j<count($data);$j++){
            $trees=$data[$j]["id"];
            $str=$data[$j]["name"];
            if($data[$j]['pid']!=0){
                $parent=getrow("select id,pid,name from jipu.{$table} where id='{$data[$j]['pid']}'");
                $trees=$parent["id"].",".$trees;
                $str=$parent["name"]."/".$str;
                if($parent['pid']!=0) {
                    $parent2=getrow("select id,pid,name from jipu.{$table} where id='{$parent['pid']}'");
                    $trees=$parent2["id"].",".$trees;;
                    $str=$parent2["name"]."/".$str;
                    if($parent2['pid']!=0) {
                        $parent3=getrow("select id,pid,name from jipu.{$table} where id='{$parent2['pid']}'");
                        $trees=$parent3["id"].",".$trees;;
                        $str=$parent3["name"]."/".$str;
                    }
                }
            }
            $result[]=array("name"=>$data[$j]["name"],"trees"=>$trees,"str"=>$str);
        }


    }
    return $result;
}

function stopChromeDriver() {
    // 尝试结束ChromeDriver进程
    $result = shell_exec("taskkill /F /IM chromedriver.exe");

    if ($result !== null) {
        echo "ChromeDriver stopped.\n";
    } else {
        echo "No ChromeDriver process found or unable to stop.\n";
    }
}

function startChromeDriver() {
    $chromedriverPath = 'C:\\chromedriver.exe';

// 使用 exec 函数执行 chromedriver.exe，并捕获输出
    $output = array();
    $returnVar = null;
    exec($chromedriverPath, $output, $returnVar);

// 检查命令是否成功执行
    if ($returnVar === 0) {
        echo "Chromedriver executed successfully.<br>";
        // 输出命令的每一行结果
        foreach ($output as $line) {
            echo $line . "<br>";
        }
    } else {
        echo "Chromedriver execution failed with return code: " . $returnVar;
    }
}

function restartChromeDriver(){
    stopChromeDriver();
    startChromeDriver();
}

function curl_post_json($url,$json){
    $host=host($url);
    $length=strlen($json);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36");
    curl_setopt($ch, CURLOPT_REFERER, "{$url}");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, "false");
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, "2");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,0);
    curl_setopt($ch, CURLOPT_VERBOSE,1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Host:{$host}",
        "Connection:keep-alive",
        "Content-Length:{$length}",
        "Accept:*/*",
        "User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
        "Content-Type:application/json",
        "Accept-Language:zh-CN,zh;q=0.9",
        "sec-ch-ua:\"Not)A;Brand\";v=\"99\", \"Google Chrome\";v=\"127\", \"Chromium\";v=\"127\"",
        "sec-ch-ua-mobile:?0",
        "sec-ch-ua-platform:\"Windows\"",
        "Sec-Fetch-Site:cross-site",
        "Sec-Fetch-Mode:cors",
        "Sec-Fetch-Dest:empty"
    ));
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_POST, true );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    $result=curl_exec($ch);
    $curlinfo=curl_getinfo( $ch, CURLINFO_HEADER_OUT)."\r\n".$json."\r\n\r\n";
    $curlinfo=preg_replace("/\s+HTTP\/2/","?XDEBUG_SESSION_START=5432543 HTTP/1.1",$curlinfo);
    $params=array();
    $params["url"]=$url;
    $params["json"]=$json;
    $params["curlinfo"]=$curlinfo;
    buginfo($params,'',$url);
    curl_close($ch);
    return $result;
}

